package com.tao.plan.controller.interceptor;

import com.auth0.jwt.interfaces.Claim;
import com.tao.plan.common.BaseThreadLocal;
import com.tao.plan.common.utils.JwtUtil;
import com.tao.plan.common.exception.TokenException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Component
public class TokenInterceptor implements HandlerInterceptor {
	@Autowired
	private JwtUtil jwtUtil;
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		String token = request.getHeader("Authorization");
		try{
			Map<String, Claim> claimMap = jwtUtil.verifyToken(token);
			String uid = claimMap.get("uid").asString().replaceAll("\"","");
			BaseThreadLocal.setUid(uid);
		}catch (Exception e){
			throw new TokenException("token异常");
		}
		return true;
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
		BaseThreadLocal.delUid();
	}
}
